# -*- coding: utf-8 -*-
# !/usr/bin/env python
# 信息系统

import sys
import re

reload(sys)
sys.setdefaultencoding('utf-8')
import json
import os
from flask import Blueprint, g, make_response, send_file, request
from psycopg2 import connect
from psycopg2.extras import RealDictCursor
from lib.validform import V, ValidateForm
from lib import auth
from lib.table import table
from config import config
from openpyxl import load_workbook
from lib.record import recodelog

app = Blueprint(__name__ + "_app", __name__)


# 连接/关闭 数据库
@app.before_request
def setupdb():
    g.conn = connect(**config.DatabaseConfig.siem)
    g.cursor = g.conn.cursor(cursor_factory=RealDictCursor)


@app.teardown_request
def unsetdb(exception):
    if g.cursor:
        g.cursor.close()
        g.cursor = None
    if g.conn:
        g.conn.close()
        g.conn = None


# 获取h_infomation_system
@app.route('/api/information/showinfo', methods=["POST"])
@auth.permission('informationSystem', 'readOnly')
def getwebsiteinfo(_currUser):
    try:
        tb = table()
        g.cursor.execute(
            """select a.info_sys_name as ainfo_sys_name, a.info_sys_id as ainfo_sys_id, a.info_sys_description as ainfo_sys_description, a.info_sys_code as ainfo_sys_code, a.url as aurl, d2t(a.r_time) as ar_time, b.agency_name as bagency_name,b.agency_id as bagency_id
            from h_information_system as a 
            left join sys_agency_info as b on a.agency_id = b.agency_id
            %s %s %s %s """ % (tb.where(["a.info_sys_name"], "a.state='1'"), tb.orderBy(), tb.offset(), tb.limit()))
        rows = g.cursor.fetchall()
        g.cursor.execute("""select count(*) as num from h_information_system as a left join sys_agency_info as b on a.agency_id = b.agency_id
            %s  """ % (tb.where(["a.info_sys_name"], "a.state='1'")))
        total = g.cursor.fetchone()['num']
        return json.dumps({
            "status": "success",
            "data": {
                "total": total,
                "data": rows
            }
        })
    except Exception, e:
        return json.dumps({"status": "except", "msg": "异常", "warn": str(e)})


# 查看详情
@app.route('/api/information/more', methods=["POST"])
def more():
    try:
        form = ValidateForm(info_sys_id=['信息系统编号', V.required()])
        (flag, data) = form.validate()
        if not flag:
            data['status'] = 'fail'
            return json.dumps(data)
        g.cursor.execute("""select info_sys_id,info_sys_name,info_sys_description,info_sys_code, url, tag, maintainer, maintainer_phone, maintainer_email,d2t(r_time) as r_time,remark from h_information_system 
 where info_sys_id='%(info_sys_id)s' and state='1'""" % (data))
        return json.dumps({"status": "success", "data": g.cursor.fetchall()})
    except Exception, e:
        return json.dumps({
            "status": "except",
            "msg": "异常",
            "warn": str(e)
        })


# 获取机构详情
@app.route('/api/website/getnodenamemsg', methods=['POST'])
def mechanism_details():
    try:
        form = ValidateForm(aagency_id=['机构编号', V.optional()], )
        (flag, data) = form.validate()
        if not flag:
            data['status'] = 'fail'
            return json.dumps(data)
        g.cursor.execute(
            """ select a.agency_id as aagency_id,a.node_name as anode_name,string_agg(sn.node_name,',') as department,
               d2t(a.r_time) as ar_time ,a.r_person as ar_person,a.linkman as alinkman,a.seq||'级' as aseq, a.telephone as atelephone,a.linkman_email as alinkman_email,b.node_name as bnode_name,a.remarks as aremarks,a.state as astate,
               b.node_name as bnode_name,a.belong_area,a.province,a.city,a.area,string_agg(sn.agency_id,',') as sid,e.node_name as cnode_name,
               c.type_name,b.state as bstate from sys_node_info as a
               left join (select node_name,parent_agency_id,agency_id from sys_node_info where node_type_id = '0') as sn on sn.parent_agency_id = a.agency_id
               left join sys_node_info as b on b.agency_id = a.parent_agency_id
               left join h_dept_type_info as c on a.type_id = c.type_id
               left join sys_node_info as e on a.supervision_agency_id = e.agency_id  where a.agency_id = %(agency_id)s
               group by
               a.agency_id,a.node_name,e.node_name,
               d2t(a.r_time),a.r_person,a.linkman,a.telephone,a.linkman_email,b.node_name,a.remarks,a.state,
               b.node_name,a.belong_area,a.province,a.city,a.area,
               c.type_name,b.state
                 """, (data))
        msg = g.cursor.fetchall()
        return json.dumps({"status": "success", 'data': msg})
    except Exception, e:
        return json.dumps({
            "status": "except",
            'msg': '异常',
            "warn": str(e)
        })


@app.route('/api/information/new', methods=['POST'])
@auth.permission('informationSystem')
def get_new_count(_currUser):
    u"""查询同步信息系统变更数."""
    try:
        g.cursor.execute("""select count(1) as num from h_synchroniz_info where synchroniz_table = 'h_information_system' and person_id = '%s' and state='1' """ % (_currUser['user']['person_id']))
        return json.dumps({
            "status": "success",
            "data": g.cursor.fetchone()['num']
        })
    except Exception:
        return json.dumps({"status": "except", 'msg': '异常'})
